package com.aggregate.pay.saobei.support.client;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aggregate.pay.saobei.bean.WapPayData;
import com.aggregate.pay.saobei.support.Client;
import com.aggregate.pay.saobei.support.Factory;
import com.aggregate.pay.saobei.support.Merch;
import com.aggregate.pay.saobei.support.utils.MD5;

/**
 * 扫呗支付接口-wap支付参数
 * @author Moyq5
 * @date 2018年6月27日
 */
public class WapPay implements Client<WapPayData, String> {
	private static final Logger log = LoggerFactory.getLogger(WapPay.class);
	
	private Merch merch;
	
	public WapPay(Merch merch) {
		this.merch = merch;
	}

	@Override
	public String execute(WapPayData data) {
		Map<String, Object> map = new TreeMap<String, Object>();
		map.put("merchant_no", merch.merchantNo());
		map.put("terminal_id", merch.terminalId());
		map.put("terminal_trace", data.getTerminalTrace());
		map.put("terminal_time", new SimpleDateFormat("yyyyMMddHHmmss").format(data.getTerminalTime()));
		map.put("total_fee", data.getTotalFee());
		map.put("order_body", data.getOrderBody());
		map.put("notify_url", data.getNotifyUrl());
		map.put("front_url", data.getFrontUrl());
		map.put("auto_pay", null != data.getAutoPay() && data.getAutoPay() ? 1 : 0);
		map.put("attach", data.getAttach());
		
		StringBuffer sb = new StringBuffer();
		for (Entry<String, Object> entry: map.entrySet()) {
			if (!isEmpty(entry.getValue())) {
				sb.append(entry.getKey() + "=" + entry.getValue() + "&");
			}
		}
		sb.append("access_token=" + merch.accessToken());

		log.debug("签名内容：{}", sb.toString());
		String sign = MD5.MD5Encode(sb.toString()).toUpperCase();
		log.debug("签名值：{}", sign);
		map.put("key_sign", sign);
		
		try {
			map.put("notify_url", isEmpty(data.getNotifyUrl()) ? "" : URLEncoder.encode(data.getNotifyUrl(), "UTF-8"));
			map.put("front_url", isEmpty(data.getFrontUrl()) ? "" : URLEncoder.encode(data.getFrontUrl(), "UTF-8"));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		sb = new StringBuffer();
		for (Entry<String, Object> entry: map.entrySet()) {
			if (!isEmpty(entry.getValue())) {
				sb.append(entry.getKey() + "=" + entry.getValue() + "&");
			}
		}
		sb.delete(sb.length() - 1, sb.length());// 去掉最后的“&”
		
		return Factory.getConfig().serverPath() + "/open/wap/110/pay" + "?" + sb.toString();
	}
	
	private boolean isEmpty(Object obj) {
		return null == obj || String.valueOf(obj).trim().isEmpty();
	}

}
